package user_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/blog_type"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

type UserModelRequest struct {
	NickName string         `json:"nick_name" binding:"required" msg:"请输入昵称"`     // 昵称
	UserName string         `json:"user_name" binding:"required" msg:"请输入用户名"`    // 用户名
	Password string         `json:"password" binding:"required" msg:"请输入密码"`      // 密码
	TwPwd    string         `json:"tw_pwd" binding:"required" msg:"请再次输入密码"`      // 二次密码
	Avatar   string         `json:"avatar" binding:"required" msg:"请上传头像"`        // 头像
	Email    string         `json:"email" binding:"required,email" msg:"请输入正确邮箱"` // 邮箱
	Tel      string         `json:"tel" binding:"required" msg:"请输入联系方式"`         // 电话
	Addr     string         `json:"addr" binding:"required" msg:"请输入地址"`          // 地址
	Role     blog_type.Role `json:"role" binding:"required" msg:"请选择用户权限"`        // 用户权限 1 管理人 2 用户 3 游客
}

func (UserApi) UserCreateView(c *gin.Context) {
	var cr UserModelRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	if cr.Password != cr.TwPwd {
		http.FailWithMessage("两次密码输入不一致", c)
		return
	}

	user := new(models.UserModel)
	// 判断用户名
	err := common.DB.Take(&user, "user_name = ?", cr.UserName).Error
	if err == nil {
		http.FailWithMessage("用户名已存在", c)
		return
	}
	hashPwd, _ := utils.HashPwd(cr.Password)
	// 添加用户
	userCreate := &models.UserModel{
		NickName:   cr.NickName,
		UserName:   cr.UserName,
		Password:   hashPwd,
		Avatar:     cr.Avatar,
		Email:      cr.Email,
		Tel:        cr.Tel,
		Addr:       cr.Addr,
		Ip:         c.ClientIP(),
		Role:       cr.Role,
		SignStatus: blog_type.LoginTypeEmail,
	}

	err = common.DB.Create(&userCreate).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("添加失败", c)
		return
	}
	http.IsOkWithMessage("添加成功", c)
}
